<template>
  <div class="security-benchmarks-container">
    <el-card class="benchmarks-card">
      <template #header>
        <div class="card-header">
          <h2>安全基准管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateBenchmarkDialog = true">
              <el-icon><Plus /></el-icon>
              新建基准
            </el-button>
            <el-button @click="importBenchmark">
              <el-icon><Upload /></el-icon>
              导入基准
            </el-button>
            <el-button @click="exportSelectedBenchmarks">
              <el-icon><Download /></el-icon>
              导出选中
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-filter-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索基准名称、描述或标准"
              prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="filterCategory"
              placeholder="选择类别"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="category in benchmarkCategories"
                :key="category.value"
                :label="category.label"
                :value="category.value"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="filterStatus"
              placeholder="选择状态"
              clearable
              @change="handleFilter"
            >
              <el-option label="已启用" value="enabled" />
              <el-option label="已禁用" value="disabled" />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <!-- 基准列表 -->
      <div class="benchmarks-table-container">
        <el-table
          v-loading="loading"
          :data="filteredBenchmarks"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @row-dblclick="editBenchmark"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="基准名称" min-width="180">
            <template #default="scope">
              <div class="benchmark-name-cell">
                <div class="benchmark-name">{{ scope.row.name }}</div>
                <div class="benchmark-category">
                  <el-tag size="small" :type="getCategoryType(scope.row.category)">
                    {{ getCategoryLabel(scope.row.category) }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="standard" label="安全标准" width="150" />
          <el-table-column prop="ruleCount" label="规则数量" width="100" align="center">
            <template #default="scope">
              <el-badge :value="scope.row.ruleCount" type="primary" />
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200">
            <template #default="scope">
              <div class="benchmark-description" :title="scope.row.description">
                {{ scope.row.description }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createdBy" label="创建者" width="120" />
          <el-table-column prop="createdAt" label="创建时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="enabled"
                inactive-value="disabled"
                active-text="启用"
                inactive-text="禁用"
                @change="updateBenchmarkStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="editBenchmark(scope.row)"
                size="small"
                title="编辑基准"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="primary"
                link
                @click="manageRules(scope.row)"
                size="small"
                title="管理规则"
              >
                <el-icon><List /></el-icon>
              </el-button>
              <el-button
                type="danger"
                link
                @click="deleteBenchmark(scope.row)"
                size="small"
                title="删除基准"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredBenchmarks.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑基准对话框 -->
    <el-dialog
      v-model="showCreateBenchmarkDialog"
      :title="editingBenchmark ? '编辑安全基准' : '新建安全基准'"
      width="600px"
      @close="resetBenchmarkForm"
    >
      <el-form
        ref="benchmarkFormRef"
        :model="benchmarkForm"
        :rules="benchmarkFormRules"
        label-width="120px"
      >
        <el-form-item label="基准名称" prop="name">
          <el-input
            v-model="benchmarkForm.name"
            placeholder="请输入基准名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="安全标准" prop="standard">
          <el-input
            v-model="benchmarkForm.standard"
            placeholder="请输入安全标准（如CIS、OWASP Top 10等）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select
            v-model="benchmarkForm.category"
            placeholder="请选择基准类别"
          >
            <el-option
              v-for="category in benchmarkCategories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="benchmarkForm.description"
            type="textarea"
            placeholder="请输入基准描述"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch
            v-model="benchmarkForm.status"
            active-value="enabled"
            inactive-value="disabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateBenchmarkDialog = false">取消</el-button>
          <el-button type="primary" @click="saveBenchmark">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 规则管理对话框 -->
    <el-dialog
      v-model="showRuleManagementDialog"
      :title="`管理规则 - ${selectedBenchmark?.name}`"
      width="800px"
    >
      <div class="rule-management-container">
        <!-- 规则搜索和筛选 -->
        <div class="rule-search-filter">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-input
                v-model="ruleSearchQuery"
                placeholder="搜索规则ID、名称或描述"
                prefix-icon="Search"
                clearable
              />
            </el-col>
            <el-col :span="8">
              <el-select
                v-model="ruleSeverityFilter"
                placeholder="按严重程度筛选"
                clearable
              >
                <el-option label="高危" value="high" />
                <el-option label="中危" value="medium" />
                <el-option label="低危" value="low" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="showAddRuleDialog = true">
                <el-icon><Plus /></el-icon>
                添加规则
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 规则列表 -->
        <div class="rules-table-container">
          <el-table
            v-loading="rulesLoading"
            :data="filteredRules"
            style="width: 100%"
            @row-dblclick="editRule"
          >
            <el-table-column prop="id" label="规则ID" width="100" />
            <el-table-column prop="name" label="规则名称" min-width="200">
              <template #default="scope">
                <div class="rule-name-cell">
                  <div class="rule-name">{{ scope.row.name }}</div>
                  <div class="rule-severity">
                    <el-tag size="small" :type="getSeverityType(scope.row.severity)">
                      {{ scope.row.severity }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="checkType" label="检查类型" width="120" />
            <el-table-column prop="description" label="规则描述" min-width="250">
              <template #default="scope">
                <div class="rule-description" :title="scope.row.description">
                  {{ scope.row.description }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="enabled"
                  inactive-value="disabled"
                  @change="updateRuleStatus(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  @click="editRule(scope.row)"
                  size="small"
                  title="编辑规则"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button
                  type="danger"
                  link
                  @click="deleteRule(scope.row)"
                  size="small"
                  title="删除规则"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 规则分页 -->
        <div class="rule-pagination-container">
          <el-pagination
            v-model:current-page="ruleCurrentPage"
            v-model:page-size="rulePageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredRules.length"
            @size-change="handleRuleSizeChange"
            @current-change="handleRuleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRuleManagementDialog = false">关闭</el-button>
          <el-button type="primary" @click="importRules">导入规则</el-button>
          <el-button type="primary" @click="exportRules">导出规则</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      v-model="showAddRuleDialog"
      :title="editingRule ? '编辑规则' : '添加规则'"
      width="600px"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleFormRules"
        label-width="120px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入规则名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="规则ID" prop="id" v-if="!editingRule">
          <el-input
            v-model="ruleForm.id"
            placeholder="请输入规则ID（如CIS-1.1.1）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-radio-group v-model="ruleForm.severity">
            <el-radio-button label="high">高危</el-radio-button>
            <el-radio-button label="medium">中危</el-radio-button>
            <el-radio-button label="low">低危</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检查类型" prop="checkType">
          <el-select
            v-model="ruleForm.checkType"
            placeholder="请选择检查类型"
          >
            <el-option label="配置检查" value="config" />
            <el-option label="漏洞扫描" value="vulnerability" />
            <el-option label="合规性检查" value="compliance" />
            <el-option label="安全最佳实践" value="best_practice" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则描述" prop="description">
          <el-input
            v-model="ruleForm.description"
            type="textarea"
            placeholder="请输入规则详细描述"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="检查逻辑" prop="checkLogic">
          <el-input
            v-model="ruleForm.checkLogic"
            type="textarea"
            placeholder="请输入检查逻辑或查询语句"
            :rows="4"
            maxlength="1000"
            show-word-limit
          />
          <div class="form-hint">支持正则表达式、SQL查询或自定义检查脚本</div>
        </el-form-item>
        <el-form-item label="修复建议" prop="remediation">
          <el-input
            v-model="ruleForm.remediation"
            type="textarea"
            placeholder="请输入修复建议"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch
            v-model="ruleForm.status"
            active-value="enabled"
            inactive-value="disabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddRuleDialog = false">取消</el-button>
          <el-button type="primary" @click="saveRule">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, List, Upload, Download, Search } from '@element-plus/icons-vue'
import apiService from '../services/apiService.js'
import { formatDate } from '../utils/dateUtils.js'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const filterCategory = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selectedBenchmarks = ref([])
const showCreateBenchmarkDialog = ref(false)
const showRuleManagementDialog = ref(false)
const showAddRuleDialog = ref(false)
const editingBenchmark = ref(null)
const editingRule = ref(null)
const selectedBenchmark = ref(null)
const rulesLoading = ref(false)
const ruleSearchQuery = ref('')
const ruleSeverityFilter = ref('')
const ruleCurrentPage = ref(1)
const rulePageSize = ref(10)
const allBenchmarks = ref([])
const allRules = ref([])

// 基准表单
const benchmarkForm = reactive({
  name: '',
  standard: '',
  category: '',
  description: '',
  status: 'enabled'
})

// 规则表单
const ruleForm = reactive({
  id: '',
  name: '',
  severity: 'medium',
  checkType: 'config',
  description: '',
  checkLogic: '',
  remediation: '',
  status: 'enabled'
})

// 表单验证规则
const benchmarkFormRules = {
  name: [
    { required: true, message: '请输入基准名称', trigger: 'blur' }
  ],
  standard: [
    { required: true, message: '请输入安全标准', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择基准类别', trigger: 'change' }
  ]
}

const ruleFormRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  id: [
    { required: true, message: '请输入规则ID', trigger: 'blur' },
    { validator: validateRuleId, trigger: 'blur' }
  ],
  severity: [
    { required: true, message: '请选择严重程度', trigger: 'change' }
  ],
  checkType: [
    { required: true, message: '请选择检查类型', trigger: 'change' }
  ],
  checkLogic: [
    { required: true, message: '请输入检查逻辑', trigger: 'blur' }
  ]
}

// 基准类别选项
const benchmarkCategories = [
  { label: '操作系统', value: 'os' },
  { label: '网络安全', value: 'network' },
  { label: 'Web应用', value: 'web' },
  { label: '数据库', value: 'database' },
  { label: '云服务', value: 'cloud' },
  { label: '容器安全', value: 'container' },
  { label: '移动应用', value: 'mobile' },
  { label: '身份认证', value: 'auth' },
  { label: '加密安全', value: 'encryption' },
  { label: '其他', value: 'other' }
]

// 计算属性
const filteredBenchmarks = computed(() => {
  let result = [...allBenchmarks.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(benchmark => 
      benchmark.name.toLowerCase().includes(query) ||
      benchmark.description.toLowerCase().includes(query) ||
      benchmark.standard.toLowerCase().includes(query)
    )
  }
  
  // 类别过滤
  if (filterCategory.value) {
    result = result.filter(benchmark => benchmark.category === filterCategory.value)
  }
  
  // 状态过滤
  if (filterStatus.value) {
    result = result.filter(benchmark => benchmark.status === filterStatus.value)
  }
  
  return result
})

const filteredRules = computed(() => {
  let result = [...allRules.value]
  
  // 搜索过滤
  if (ruleSearchQuery.value) {
    const query = ruleSearchQuery.value.toLowerCase()
    result = result.filter(rule => 
      rule.id.toLowerCase().includes(query) ||
      rule.name.toLowerCase().includes(query) ||
      rule.description.toLowerCase().includes(query)
    )
  }
  
  // 严重程度过滤
  if (ruleSeverityFilter.value) {
    result = result.filter(rule => rule.severity === ruleSeverityFilter.value)
  }
  
  return result
})

// 方法
const loadBenchmarks = async () => {
  loading.value = true
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.getSecurityBenchmarks()
    // allBenchmarks.value = response
    
    // 模拟数据
    allBenchmarks.value = [
      {
        id: '1',
        name: 'CIS Linux 安全基准',
        standard: 'CIS',
        category: 'os',
        ruleCount: 128,
        description: 'CIS Linux操作系统安全配置最佳实践基准，包含系统强化、访问控制等方面的安全检查规则',
        createdBy: 'admin',
        createdAt: '2024-01-15T10:30:00Z',
        status: 'enabled'
      },
      {
        id: '2',
        name: 'OWASP Top 10 检查',
        standard: 'OWASP',
        category: 'web',
        ruleCount: 24,
        description: '基于OWASP Top 10的Web应用安全检查规则，覆盖常见Web应用漏洞',
        createdBy: 'security_team',
        createdAt: '2024-01-18T14:20:00Z',
        status: 'enabled'
      },
      {
        id: '3',
        name: '数据库安全配置',
        standard: '内部标准',
        category: 'database',
        ruleCount: 45,
        description: '针对MySQL、PostgreSQL等数据库的安全配置检查规则',
        createdBy: 'dba_team',
        createdAt: '2024-01-20T09:15:00Z',
        status: 'enabled'
      },
      {
        id: '4',
        name: '容器安全检查',
        standard: 'CIS Docker',
        category: 'container',
        ruleCount: 36,
        description: '容器安全配置检查规则，基于CIS Docker Benchmark',
        createdBy: 'devops_team',
        createdAt: '2024-01-22T16:45:00Z',
        status: 'disabled'
      },
      {
        id: '5',
        name: '网络设备安全基准',
        standard: 'CIS Network',
        category: 'network',
        ruleCount: 78,
        description: '网络设备安全配置检查规则，包含路由器、交换机等设备的安全配置',
        createdBy: 'network_team',
        createdAt: '2024-01-25T11:30:00Z',
        status: 'enabled'
      }
    ]
  } catch (error) {
    console.error('加载安全基准失败:', error)
    ElMessage.error('加载安全基准失败，请重试')
  } finally {
    loading.value = false
  }
}

const loadRules = async (benchmarkId) => {
  rulesLoading.value = true
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.getBenchmarkRules(benchmarkId)
    // allRules.value = response
    
    // 模拟数据
    const mockRules = {
      '1': [
        {
          id: 'CIS-1.1.1',
          name: '确保/etc/passwd权限设置正确',
          severity: 'high',
          checkType: 'config',
          description: '验证/etc/passwd文件权限是否为644或更严格',
          checkLogic: 'stat -c %a /etc/passwd | grep -E "^(4|6)44$"',
          remediation: '运行命令: chmod 644 /etc/passwd',
          status: 'enabled'
        },
        {
          id: 'CIS-1.1.2',
          name: '确保/etc/shadow权限设置正确',
          severity: 'high',
          checkType: 'config',
          description: '验证/etc/shadow文件权限是否为000或更严格',
          checkLogic: 'stat -c %a /etc/shadow | grep -E "^000$"',
          remediation: '运行命令: chmod 000 /etc/shadow',
          status: 'enabled'
        },
        {
          id: 'CIS-1.2.1',
          name: '禁用不需要的系统服务',
          severity: 'medium',
          checkType: 'config',
          description: '检查并禁用不必要的系统服务，减少攻击面',
          checkLogic: 'systemctl list-unit-files --type=service | grep enabled',
          remediation: '使用systemctl disable命令禁用不必要的服务',
          status: 'enabled'
        }
      ],
      '2': [
        {
          id: 'OWASP-1',
          name: '防止SQL注入',
          severity: 'high',
          checkType: 'vulnerability',
          description: '检查应用程序是否存在SQL注入漏洞',
          checkLogic: '检测参数中是否包含SQL注入特征字符串',
          remediation: '使用参数化查询或ORM框架',
          status: 'enabled'
        },
        {
          id: 'OWASP-2',
          name: '防止跨站脚本攻击(XSS)',
          severity: 'high',
          checkType: 'vulnerability',
          description: '检查应用程序是否存在XSS漏洞',
          checkLogic: '检测输入是否经过正确过滤和转义',
          remediation: '对所有用户输入进行严格过滤和输出转义',
          status: 'enabled'
        }
      ],
      '3': [
        {
          id: 'DB-1.1',
          name: '禁用MySQL远程root登录',
          severity: 'high',
          checkType: 'config',
          description: '确保MySQL不允许root用户远程登录',
          checkLogic: "SELECT user,host FROM mysql.user WHERE user='root' AND host!='localhost' AND host!='127.0.0.1' AND host!='::1'",
          remediation: '删除远程root账户或限制为特定IP',
          status: 'enabled'
        }
      ],
      '4': [
        {
          id: 'DOCKER-1.1',
          name: '使用非root用户运行容器',
          severity: 'high',
          checkType: 'config',
          description: '确保容器以非root用户身份运行',
          checkLogic: '检查Dockerfile中的USER指令或容器运行时用户',
          remediation: '在Dockerfile中添加USER指令或使用--user参数',
          status: 'disabled'
        }
      ],
      '5': [
        {
          id: 'NET-1.1',
          name: '禁用路由器SNMP默认团体名',
          severity: 'high',
          checkType: 'config',
          description: '确保网络设备不使用默认SNMP团体名',
          checkLogic: '检查SNMP配置中的团体名设置',
          remediation: '修改SNMP配置，使用强密码作为团体名',
          status: 'enabled'
        }
      ]
    }
    
    allRules.value = mockRules[benchmarkId] || []
  } catch (error) {
    console.error('加载规则失败:', error)
    ElMessage.error('加载规则失败，请重试')
  } finally {
    rulesLoading.value = false
  }
}

const saveBenchmark = async () => {
  // 验证表单
  const benchmarkFormRef = ref(null)
  if (!benchmarkFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    if (editingBenchmark.value) {
      // 更新现有基准
      const index = allBenchmarks.value.findIndex(b => b.id === editingBenchmark.value.id)
      if (index !== -1) {
        allBenchmarks.value[index] = { ...benchmarkForm, id: editingBenchmark.value.id }
      }
      ElMessage.success('安全基准更新成功')
    } else {
      // 创建新基准
      const newBenchmark = {
        ...benchmarkForm,
        id: String(allBenchmarks.value.length + 1),
        ruleCount: 0,
        createdBy: 'admin',
        createdAt: new Date().toISOString()
      }
      allBenchmarks.value.unshift(newBenchmark)
      ElMessage.success('安全基准创建成功')
    }
    
    showCreateBenchmarkDialog.value = false
    resetBenchmarkForm()
  } catch (error) {
    console.error('保存安全基准失败:', error)
    ElMessage.error('保存安全基准失败，请重试')
  }
}

const saveRule = async () => {
  // 验证表单
  const ruleFormRef = ref(null)
  if (!ruleFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    if (editingRule.value) {
      // 更新现有规则
      const index = allRules.value.findIndex(r => r.id === editingRule.value.id)
      if (index !== -1) {
        allRules.value[index] = { ...ruleForm }
      }
      ElMessage.success('规则更新成功')
    } else {
      // 创建新规则
      const newRule = {
        ...ruleForm
      }
      allRules.value.unshift(newRule)
      
      // 更新基准的规则数量
      const benchmarkIndex = allBenchmarks.value.findIndex(b => b.id === selectedBenchmark.value.id)
      if (benchmarkIndex !== -1) {
        allBenchmarks.value[benchmarkIndex].ruleCount++
      }
      
      ElMessage.success('规则创建成功')
    }
    
    showAddRuleDialog.value = false
    resetRuleForm()
  } catch (error) {
    console.error('保存规则失败:', error)
    ElMessage.error('保存规则失败，请重试')
  }
}

const deleteBenchmark = async (benchmark) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除安全基准"${benchmark.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里模拟API调用，实际项目中应该调用真实API
    allBenchmarks.value = allBenchmarks.value.filter(b => b.id !== benchmark.id)
    ElMessage.success('安全基准删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const deleteRule = async (rule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则"${rule.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里模拟API调用，实际项目中应该调用真实API
    allRules.value = allRules.value.filter(r => r.id !== rule.id)
    
    // 更新基准的规则数量
    const benchmarkIndex = allBenchmarks.value.findIndex(b => b.id === selectedBenchmark.value.id)
    if (benchmarkIndex !== -1 && allBenchmarks.value[benchmarkIndex].ruleCount > 0) {
      allBenchmarks.value[benchmarkIndex].ruleCount--
    }
    
    ElMessage.success('规则删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const updateBenchmarkStatus = async (benchmark) => {
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    ElMessage.success(`安全基准已${benchmark.status === 'enabled' ? '启用' : '禁用'}`)
  } catch (error) {
    // 回滚状态更改
    benchmark.status = benchmark.status === 'enabled' ? 'disabled' : 'enabled'
    console.error('更新基准状态失败:', error)
    ElMessage.error('更新基准状态失败，请重试')
  }
}

const updateRuleStatus = async (rule) => {
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    ElMessage.success(`规则已${rule.status === 'enabled' ? '启用' : '禁用'}`)
  } catch (error) {
    // 回滚状态更改
    rule.status = rule.status === 'enabled' ? 'disabled' : 'enabled'
    console.error('更新规则状态失败:', error)
    ElMessage.error('更新规则状态失败，请重试')
  }
}

const editBenchmark = (benchmark) => {
  editingBenchmark.value = benchmark
  Object.assign(benchmarkForm, benchmark)
  showCreateBenchmarkDialog.value = true
}

const editRule = (rule) => {
  editingRule.value = rule
  Object.assign(ruleForm, rule)
  showAddRuleDialog.value = true
}

const manageRules = (benchmark) => {
  selectedBenchmark.value = benchmark
  showRuleManagementDialog.value = true
  loadRules(benchmark.id)
}

const importBenchmark = () => {
  // 这里应该实现导入功能，打开文件选择器
  ElMessage.info('导入基准功能待实现')
}

const exportSelectedBenchmarks = () => {
  if (selectedBenchmarks.value.length === 0) {
    ElMessage.warning('请选择要导出的安全基准')
    return
  }
  
  // 这里应该实现导出功能
  ElMessage.success(`已导出${selectedBenchmarks.value.length}个安全基准`)
}

const importRules = () => {
  // 这里应该实现导入规则功能
  ElMessage.info('导入规则功能待实现')
}

const exportRules = () => {
  // 这里应该实现导出规则功能
  ElMessage.success(`已导出${allRules.value.length}条规则`)
}

const handleSelectionChange = (selection) => {
  selectedBenchmarks.value = selection
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newCurrent) => {
  currentPage.value = newCurrent
}

const handleRuleSizeChange = (newSize) => {
  rulePageSize.value = newSize
}

const handleRuleCurrentChange = (newCurrent) => {
  ruleCurrentPage.value = newCurrent
}

const resetBenchmarkForm = () => {
  benchmarkForm.name = ''
  benchmarkForm.standard = ''
  benchmarkForm.category = ''
  benchmarkForm.description = ''
  benchmarkForm.status = 'enabled'
  editingBenchmark.value = null
}

const resetRuleForm = () => {
  ruleForm.id = ''
  ruleForm.name = ''
  ruleForm.severity = 'medium'
  ruleForm.checkType = 'config'
  ruleForm.description = ''
  ruleForm.checkLogic = ''
  ruleForm.remediation = ''
  ruleForm.status = 'enabled'
  editingRule.value = null
}

const validateRuleId = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入规则ID'))
    return
  }
  
  // 检查规则ID是否重复
  const exists = allRules.value.some(r => r.id === value && (!editingRule.value || r.id !== editingRule.value.id))
  if (exists) {
    callback(new Error('规则ID已存在'))
  } else {
    callback()
  }
}

// 辅助函数
const getCategoryType = (category) => {
  const typeMap = {
    'os': 'primary',
    'network': 'success',
    'web': 'warning',
    'database': 'danger',
    'cloud': 'info',
    'container': 'purple',
    'mobile': 'pink',
    'auth': 'teal',
    'encryption': 'indigo',
    'other': 'default'
  }
  return typeMap[category] || 'default'
}

const getCategoryLabel = (category) => {
  const labelMap = benchmarkCategories.reduce((map, cat) => {
    map[cat.value] = cat.label
    return map
  }, {})
  return labelMap[category] || category
}

const getSeverityType = (severity) => {
  const typeMap = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  }
  return typeMap[severity] || 'info'
}

// 组件挂载时加载数据
onMounted(() => {
  loadBenchmarks()
})
</script>

<style scoped>
.security-benchmarks-container {
  padding: 20px;
}

.benchmarks-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter-container {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.benchmarks-table-container,
.rules-table-container {
  overflow-x: auto;
}

.pagination-container,
.rule-pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.benchmark-name-cell,
.rule-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.benchmark-name,
.rule-name {
  font-weight: 500;
}

.benchmark-description,
.rule-description {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.rule-management-container {
  max-height: 600px;
  overflow-y: auto;
}

.rule-search-filter {
  margin-bottom: 16px;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .security-benchmarks-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .search-filter-container {
    padding: 12px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .el-col {
    width: 100% !important;
  }
}
</style>